package com.zhu.storesmanager;

import java.util.ArrayList;
import java.util.List;

import com.zhu.storesmanager.models.ModelItem;
import com.zhu.storesmanager.models.SyncModel;
import com.zhu.storesmanager.network.DownloadService;
import com.zhu.storesmanager.network.HttpConnectionMethod;
import com.zhu.storesmanager.network.HttpUtil;
import com.zhu.storesmanager.network.NetworkCallback;
import com.zhu.storesmanager.network.ParseNetworkData;
import com.zhu.storesmanager.provider.StoresManagerSettings;
import com.zhu.storesmanager.utils.Actions;
import com.zhu.storesmanager.utils.DataUtils;
import com.zhu.storesmanager.utils.DatabaseUtil;
import com.zhu.storesmanager.utils.SalesData;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 销量上报界面
 */
public class SalesReportActivity extends Activity implements View.OnClickListener{

	private final static int PUT_DIALOG = 0; //上传进度提示dialog ID

	private final static int QEQUEST_INQUIRTY = 1; //查询结果返回

	//异步查询数据库token
	private final static int MODEL_LIST_QUERY_TOKEN = 0; //查询所有型号 token  

	private TextView mTitleView = null; //标题栏
	private LinearLayout mBodyView = null; //所有型号列表内容界面
	private List<ModelItem> mModelList = new ArrayList<ModelItem>(); //所有型号列表集合
	private DataQueryHandler mDataQueryHandler = null; //数据异步查询Handler
	private Handler mHander = new Handler();
	private boolean isDataChange = false; //数据是否发生变化

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_salesreport); //设置显示界面布局
		setupViews();
		initData();
	}

	/**
	 * 初始化界面
	 */
	private void setupViews(){
		mTitleView = (TextView)findViewById(R.id.title_text);
		mBodyView = (LinearLayout)findViewById(R.id.list_body);
		//设置按钮响应监听
		findViewById(R.id.slreport_search_button).setOnClickListener(this);
		findViewById(R.id.slreport_menu_back).setOnClickListener(this);
		findViewById(R.id.slreport_menu_putdata).setOnClickListener(this);
		findViewById(R.id.slreport_menu_save).setOnClickListener(this);
	}

	/**
	 * 初始化数据
	 */
	private void initData(){
		mTitleView.setText(this.getString(R.string.salesreport_title, DataUtils.mUserData.mRealName));
		mDataQueryHandler = new DataQueryHandler(getContentResolver());
		//startQueryModelsList();
		updateListFromLocal();
	}

	/**
	 * (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if(arg0 != null){
			switch(arg0.getId()){
				case R.id.slreport_search_button: //查询
					gotoSearch();
					break;
				case R.id.slreport_menu_back: //返回
					if(!doBack()){
					    finish();
					}
					break;
				case R.id.slreport_menu_putdata: //上传
					putData();
					break;
				case R.id.slreport_menu_save: //保存
					saveData(false);
					break;
			}
		}
	}

	/**
	 * 查询
	 */
	private void gotoSearch(){
		String model = ((EditText)findViewById(R.id.slreport_search_model)).getText().toString(); //获取型号输入框数据
		String pfl = ((EditText)findViewById(R.id.slreport_search_pel)).getText().toString(); //获取PEL输入框数据
		//检查内容是合法
		if(DataUtils.checkInputSearch(model, pfl)){
			//跳转查询结果界面
			Intent intent = new Intent();
			intent.setClass(this, SalesInquiryResultActivity.class);
			intent.putExtra(SalesInquiryResultActivity.MODEL, model); //传递查询条件 model
			intent.putExtra(SalesInquiryResultActivity.PFL, pfl); //传递查询条件 pel
			startActivityForResult(intent, QEQUEST_INQUIRTY);
			return;
		}
		Actions.toastShort(this, getString(R.string.search_fail));
	}

//	/**
//	 * 开始查询型号列表
//	 */
//	private void startQueryModelsList(){
//		mDataQueryHandler.startQuery(MODEL_LIST_QUERY_TOKEN, null, 
//				StoresManagerSettings.ModelsColumns.CONTENT_URI_NO_NOTIFICATION,
//				null, null, null, null);
//	}
//	
//	/**
//	 * 更具查询结果更新型号列表
//	 * @param cursor 查询结果数据
//	 */
//	private void updateModelListFromCursor(Cursor cursor){
//		if(mModelList != null){
//			mModelList.clear(); //清空数据
//		}
//		try {
//            final int modleNameIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.ModelsColumns.MODELS_NAME);
//            while (cursor.moveToNext()) {
//            	ModelItem item = new ModelItem();
//            	item.mName = cursor.getString(modleNameIndex);
//            	mModelList.add(item);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            Log.e("zhu", "updateModelListFromCursor error");
//        } finally {
//        	if(cursor != null){
//        		cursor.close();
//        		cursor = null;
//        	}
//        }
//		updateBodyList();
//	}

	/**
	 * 更新型号列表界面
	 */
	private void updateBodyList(){
		if(mBodyView != null){
			mBodyView.removeAllViews();
		}
		for(int i = 0; i < mModelList.size(); i++){
			View view = getView(mModelList.get(i));
			mBodyView.addView(view);
		}
	}

	/**
     * 获取型号列表项界面
     * @param item 型号数据
     */
	private View getView(ModelItem item) {
        View view = LayoutInflater.from(this).inflate(R.layout.model_item, null);
        ((TextView)view.findViewById(R.id.model_name)).setText(item.mName);
        EditText edittext = (EditText)view.findViewById(R.id.model_text);
        EditText priceedittext = (EditText)view.findViewById(R.id.model_price);
        if(item.mQuantity != Integer.MIN_VALUE){
        	edittext.setText("" + item.mQuantity);
        }
        if(item.mPrice != Integer.MIN_VALUE){
        	priceedittext.setText("" + item.mPrice);
        }
        priceedittext.addTextChangedListener(mTextEditorWatcher);
        edittext.addTextChangedListener(mTextEditorWatcher);
        view.setTag(item);
        return view;
    }

	/**
	 * 异步数据查询
	 */
	private final class DataQueryHandler extends AsyncQueryHandler {
        public DataQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        /**
         * 查询结果返回
         * (non-Javadoc)
         * @see android.content.AsyncQueryHandler#onQueryComplete(int, java.lang.Object, android.database.Cursor)
         */
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
                case MODEL_LIST_QUERY_TOKEN:
                	//updateModelListFromCursor(cursor);
                    break;
                default:
                    Log.e("zhu", "onQueryComplete called with unknown token " + token);
            }
        }

        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {

        }
    }

	/**
	 * @param requestCode 请求代码
	 * @param resultCode 返回状态
	 * @param data 返回数据
	 * (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		if(resultCode != Activity.RESULT_OK){
			return;
		}
		switch(requestCode){
			case QEQUEST_INQUIRTY:
				updateListFromLocal();
				break;
		}
	}

	/**
	 * 从本地保存的数据更新界面
	 */
	private void updateListFromLocal(){
		if(mModelList != null){
			mModelList.clear();
			mModelList = null;
		}
		mModelList = SalesData.getInstance(this).getSavedModelList();
		updateBodyList();
	}

	/**
	 * 保存数据
	 */
	private void saveData(boolean isFinish){
		SalesInquiryResultActivity.saveData(this, mBodyView, true);
		isDataChange = false;
		if(isFinish){
		    finish();
		}
	}

	/**
	 * 实时上报数据
	 */
	private void putData(){
		if(DataUtils.mUserData.isOffline){//检测是否离线模式登录
			Actions.toastShort(this, getString(R.string.offlineloginnotsync));
			return;
		}
		if(mBodyView != null && mBodyView.getChildCount() > 0){//获取当前所有输入的销量数据
			List<ModelItem> list = new ArrayList<ModelItem>();
			for(int i = 0; i < mBodyView.getChildCount(); i++){
				View v = mBodyView.getChildAt(i);
				ModelItem item = (ModelItem)v.getTag();
				EditText text = (EditText)v.findViewById(R.id.model_text);//获取填入的销量数据
				EditText priceText = (EditText)v.findViewById(R.id.model_price);//获取填入的价格数据
				int curCount = SalesInquiryResultActivity.getValue(text); //读取销量
				int price = SalesInquiryResultActivity.getValue(priceText); //读取价格

				if(curCount != Integer.MIN_VALUE && price != Integer.MIN_VALUE){//数据不为空则加入上报数据集合
					ModelItem saveItem = new ModelItem();
					saveItem.mName = item.mName;
					saveItem.mQuantity = curCount;
					saveItem.mPrice = price;
					list.add(saveItem);
				}
			}
			if(list.size() > 0){ //大于0 则上报
				showDialog(PUT_DIALOG);
				startConnect(list);
				return;
			}
		}
		Actions.toastShort(this, this.getString(R.string.datereport_fail));
	}

	/**
	 * 请求网络
	 */
	private void startConnect(final List<ModelItem> list){
    	String putContent = HttpUtil.getPutPromoterSalesContent(this, DataUtils.mUserData.mUuid, list);
    	if(putContent == null){
    		Actions.toastShort(this, this.getString(R.string.datereport_fail));
    		return;
    	}
    	new HttpConnectionMethod(new NetworkCallback(){
            public void callFinished(int status, Object result) {
                // TODO Auto-generated method stub
            	SyncModel.PromoterSalesResult parseresult = ParseNetworkData.parsePromoterSalesResult(result);
            	if(parseresult != null && parseresult.Status == SyncModel.SUCCEED){ //上报成功
            		DatabaseUtil.saveReportSalesData(SalesReportActivity.this, list, parseresult.SaleDate.getTime()); //保存数据至本地
            	}
            	doConnectResult(parseresult);
            }
         }
        ).callPost(HttpUtil.getPromoterSalesUrl(), putContent);
	}

	/**
	 * 网络请求结果处理
	 * @param result 请求结果
	 */
	private void doConnectResult(final SyncModel.PromoterSalesResult result){
		 mHander.post(new Runnable() {
	            public void run() {
	            	if(result != null && result.Status == SyncModel.SUCCEED){//上报成功 更新数据
	            		//SalesData.getInstance(SalesReportActivity.this).clearAllData();
	            		Actions.toastShort(SalesReportActivity.this, SalesReportActivity.this.getString(R.string.datereport_success_network));
	            		//updateListFromLocal();
	            	}else{
	            		Actions.toastShort(SalesReportActivity.this, SalesReportActivity.this.getString(R.string.datereport_fail_network));
	            	}
	            	dismissDialog(PUT_DIALOG);
	            }
		 });
	}

	/**
     * 上传进度提示
     */
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case PUT_DIALOG:
                ProgressDialog pd = new ProgressDialog(this);
                pd.setMessage(this.getString(R.string.putdataing)
                        + getString(R.string.please_wait));
                pd.setCancelable(false);
                pd.setCanceledOnTouchOutside(false);
                return pd;

            default:
                break;
        }
        return super.onCreateDialog(id);
    }

    /**
     * 输入框内容变化监听
     */
    private final TextWatcher mTextEditorWatcher = new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        public void afterTextChanged(Editable s) {
            isDataChange = true;
        }
    };


    /**
     * 退出提示框
     * 
     */
    private void popExitDialog() {
        Actions.alertShowDetails(this, this.getString(R.string.no_save_exit_clew),
                this.getString(R.string.no_save_exit),
                R.string.button_ok, R.string.cancel,
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                        saveData(true);
                    }
                }, new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                        SalesReportActivity.this.finish();
                    }
                });
    }

    /**
     * 处理返回键
     */
    private boolean doBack(){
        if(isDataChange){
            popExitDialog();
            return true;
        }
        return false;
    }

    /**
     * 按键事件处理
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK) { //返回
            if(!doBack()){
               finish();
            }
            return true;
        }
        return false;
    }
}
